<?php

namespace App\Http\Controllers\Admin;

use App;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller as BaseController;
use App\Http\Logic\Admin\AuthLogic;
use App\Common\Status;

class AuthController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials        = request(['account', 'pswd']);
        $params['username'] = $credentials['account'];
        $params['password'] = $credentials['pswd'];
        $admin              = AuthLogic::loginCheck($credentials);

        if (!$admin || !Hash::check($params['password'], $admin->password)) {
            return $this->error(Status::ERROR, "帐号密码错误");
        }

        if ($token = auth()->guard('admin')->attempt($params)) {
            // 令牌生成成功，设置要返回的特定字段
            $data = [
                'isLogin'    => true,
                'type'       => 0,
                'account'    => $admin->username,
                'user_id'    => $admin->id,
                'username'   => $admin->username,
                'token'      => $token,
                'token_type' => 'bearer',
                'expires_in' => auth('admin')->factory()->getTTL() * 14400,
            ];

            return $this->success(Status::SUCCESS, "登陆成功", $data);
        }
        return response()->json(['msg' => '帐号密码错误', 'status' => Status::ERROR]);
    }



    /**
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public static function getAdminInfo()
    {
        return Auth::guard('admin')->user();
    }

    /**
     * 获取admin用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function info()
    {
        $user = Auth::guard('admin')->user();
        return $this->success(Status::SUCCESS, "success", $user);
    }


    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        Auth::guard('admin')->logout();
        //        $user = Auth::guard('admin')->invalidate();
        return $this->success(Status::SUCCESS, "退出成功", []);
    }

}
